package admin

import (
	"ecms/config"
	"ecms/middlewares"
	"ecms/utils/response"
	uploader2 "ecms/utils/uploader"
	"github.com/gin-gonic/gin"
	"strings"
)

type UploadController struct {
}

// Image 上传单张图片
func (c *UploadController) Image(ctx *gin.Context) {
	uploader := uploader2.New(ctx, "file")

	// 检查上传
	if !uploader.Has() {
		response.FailJson(ctx, "请上传图片", nil)
		return
	}

	// 检查大小
	if !uploader.CheckSize(config.Upload().ImageAllowSize) {
		response.FailJson(ctx, "图片大小超过限制, 最大："+config.Upload().ImageAllowSizeDisplay, nil)
		return
	}

	// 检查扩展名
	if !uploader.CheckExt(config.Upload().ImageAllowExtensions) {
		response.FailJson(ctx, "图片扩展名不允许, 仅允许："+strings.Join(config.Upload().ImageAllowExtensions, ", "), nil)
		return
	}

	// 检查是否登录
	userInfo, has := middlewares.GetAdminUser(ctx)
	if !has {
		response.FailJson(ctx, "用户状态异常", nil)
		return
	}
	url, ok := uploader.Upload("images/" + userInfo.Username)
	if !ok {
		response.FailJson(ctx, "上传失败, 请稍后再试", nil)
		return
	}

	// TODO: 后续根据用户名的目录进行归属确权, 做文件管理系统

	response.SuccessJson(ctx, "上传成功", struct {
		Url string `json:"url"`
	}{
		Url: url,
	})
}
